package com.hkfg.controller;


import com.hkfg.domain.Blog;
import com.hkfg.service.BlogService;
import com.hkfg.service.impl.BlogServiceImpl;
import com.hkfg.service.impl.UserServiceImpl;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller   // bean
@CrossOrigin
//@RestController   // 相当于上面两个
//@RequestMapping("/blogs")  // 请求路径前缀
public class BlogController {

    @Autowired
    private BlogServiceImpl blogService;
    @Autowired
    private UserServiceImpl userService;

    /**
     * 解析用户名，根据用户名查找到用户id后，通过用户id查找其所属的blog
     * @param request
     * @return
     */
    @RequestMapping(value = "/query", method = RequestMethod.GET    )
    @ResponseBody
    public List<Blog> selectAll(HttpServletRequest request ){
        return blogService.selectUserBlog(Integer.parseInt(request.getParameter("token")));
    }


    /**
     * 新建一篇博客
     * @param
     * @return
     */
    @RequestMapping(value = "/buildblog", method = RequestMethod.POST)
    @ResponseBody
    public int buildBlog(@RequestBody Blog blog){
        System.out.println("开始新建blog");
        int result = blogService.buildBlog(blog);
        if(result > 0){
            return result;   // 成功
        }else {
            return 0;    // 失败
        }
    }

    /**
     * 根据blog的id获得blog
     * @param request
     * @return blog
     */
    @RequestMapping(value = "/getblogbyid", method = RequestMethod.GET)
    @ResponseBody
    public Blog getBlogById(HttpServletRequest request){
        Integer blogId = Integer.valueOf(request.getParameter("id"));
        return blogService.getBlogById(blogId);
    }

    /**
     * 根据id删除blog
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteblogbyid", method = RequestMethod.DELETE)
    public int deleteBlogById(String id){
        System.out.println(id);
        return blogService.deleteBlogById(Integer.parseInt(id));
    }

    /**
     * 修改博客
     * @param blog
     * @return
     */
    @RequestMapping(value = "/modifyblog", method = RequestMethod.POST)
    @ResponseBody
    public int modifyBlog(@RequestBody Blog blog){
        return blogService.modifyBlog(blog.getId(), blog.getTitle(), blog.getContent());
    }



}
